package main

import (
	"bytes"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/jlaffaye/ftp"
	"github.com/lxn/walk"
	. "github.com/lxn/walk/declarative"
)

var ftpClient *ftp.ServerConn

var mainWindow *walk.MainWindow
var topWindow *walk.MainWindow
var loginButton *walk.PushButton   //登录按钮
var currentPathEdit *walk.LineEdit //当前路径
var tableView *walk.TableView      //ftp目录
var backDir *walk.PushButton       //返回上一目录

type listData struct {
	Name       string
	Type       string
	Size       int
	ModifyTime time.Time
}

type tableModel struct {
	walk.TableModelBase
	items []*listData
}

type MyMainWindow struct {
	*walk.MainWindow
}

func NewModelData() *tableModel {
	return new(tableModel)
}

func (m *tableModel) RowCount() int {
	return len(m.items)
}

func (m *tableModel) Value(row, col int) interface{} {
	item := m.items[row]

	switch col {
	case 0:
		return item.Name

	case 1:
		return item.Type

	case 2:
		return item.Size

	case 3:
		return item.ModifyTime

	}
	panic("unexpected col")
}

func main() {

	initView()

}

//初始化ftp客户端
func initFtpClient(m *tableModel) {
	var err error
	ftpClient, err = ftp.DialTimeout("192.168.1.161:21", 5*time.Second)
	err = ftpClient.Login("ftp", "123456")
	if err != nil {
		loginButton.SetText("重新登录")
	} else {
		loginButton.SetText("登录成功")
		log.Println("登陆")
		initData(m, "/")
		changeNowShowDir()
	}
}

//初始化数据
func initData(m *tableModel, nowDir string) {
	list, err := ftpClient.List(nowDir)
	if err != nil {
		log.Println(err)
	} else {
		m.items = make([]*listData, len(list))
		for i := range m.items {
			var fileType string = ""
			switch list[i].Type {
			case 0:
				fileType = "文件"
				break
			case 1:
				fileType = "文件夹"
				break
			}
			m.items[i] = &listData{
				Name:       list[i].Name,
				Type:       fileType,
				Size:       int(list[i].Size),
				ModifyTime: list[i].Time,
			}
			log.Println(list[i])
		}
		m.PublishRowsReset()
	}

}

//返回上级目录
func goBackDir(m *tableModel) {
	log.Println(ftpClient.ChangeDirToParent())
	changeNowShowDir()
	initData(m, getCurrentPath())
}

//更改当前路径地址
func changeNowShowDir() {

	currentPathEdit.SetText(getCurrentPath())

}

//获取当前路径地址
func getCurrentPath() string {
	currentPath, err := ftpClient.CurrentDir()
	if err != nil {
		return ""
	} else {
		return currentPath
	}
}

//更换目录
func changeDir(m *tableModel, dir string) {
	newDir := getCurrentPath() + "/" + dir
	log.Println(ftpClient.ChangeDir(newDir))
	changeNowShowDir()
	initData(m, newDir)
}

//线上创建文件夹
func uploadMkdir(createDir string) {
	err := ftpClient.MakeDir(createDir)
	if err != nil {
		log.Println(err)
	}
}

//上传文件夹
func uploadDir(fileDir, createDir string) {
	filepath.Walk(fileDir, func(path string, info os.FileInfo, err error) error {

		path, err = filepath.Abs(path)
		log.Println(err)
		log.Println("path:" + path)
		log.Println(info.IsDir())
		log.Println("createDir:" + createDir)
		onlinePath := strings.Replace(path, "\\", "/", -1)
		log.Println("文件地址：" + onlinePath)

		if strings.LastIndex(createDir, "/") != 0 {
			relativePath := strings.Replace(createDir, getCurrentPath(), "", 1)
			onlinePath = getCurrentPath() + onlinePath[strings.Index(onlinePath, relativePath):]
		} else {
			onlinePath = onlinePath[strings.LastIndex(onlinePath, createDir):]
		}
		log.Println(onlinePath)
		if info.IsDir() {
			uploadMkdir(onlinePath)
		} else {
			uploadFile(path, onlinePath)
		}

		return nil
	})

}

//上传单个文件
func uploadFile(localFile, onlineFile string) {
	dir, err := ioutil.ReadFile(localFile)
	log.Println(err)
	contents := bytes.NewBuffer(dir)
	log.Println(contents)
	log.Println(ftpClient.Stor(onlineFile, contents))
}

//初始化视图
func initView() {

	mw := new(MyMainWindow)
	model := NewModelData()

	log.Println((MainWindow{
		AssignTo: &mw.MainWindow,
		Title:    "ftp",
		Size:     Size{1000, 500},
		Layout:   VBox{},
		OnDropFiles: func(file []string) {
			log.Println(file)
			var onlineFile string
			for _, v := range file {
				fileInfo, err := os.Stat(v)
				log.Println("获取dir是否是文件：", err)
				v := strings.Replace(v, "\\", "/", -1)
				if getCurrentPath() == "/" {
					onlineFile = getCurrentPath() + v[strings.LastIndex(v, "/")+1:]
				} else {
					onlineFile = getCurrentPath() + v[strings.LastIndex(v, "/"):]
				}
				if fileInfo.IsDir() {
					uploadDir(v, onlineFile)
				} else {
					uploadFile(v, onlineFile)
				}

			}

		},
		Children: []Widget{
			PushButton{
				AssignTo: &loginButton,
				Text:     "点击登录",
				OnClicked: func() {
					initFtpClient(model)
				},
			},
			LineEdit{
				AssignTo:  &currentPathEdit,
				Text:      "当前路径",
				MinSize:   Size{100, 20},
				MaxSize:   Size{1000, 20},
				TextColor: walk.RGB(0, 0, 0),
			},
			PushButton{
				AssignTo: &backDir,
				Text:     "返回上一目录",
				OnClicked: func() {
					goBackDir(model)

				},
			},
			TableView{
				AssignTo:              &tableView,
				AlternatingRowBGColor: walk.RGB(239, 239, 239),
				Columns: []TableViewColumn{
					{Title: "名称", Width: 200},
					{Title: "文件类型"},
					{Title: "大小"},
					{Title: "修改时间", Format: "2006-01-02 15:04:05", Width: 200},
				},
				Model: model,
				OnItemActivated: func() {
					currentIndex := tableView.CurrentIndex()

					if model.items[currentIndex].Type == "文件夹" {
						changeDir(model, model.items[currentIndex].Name)
					}

					log.Println("双击", currentIndex)
				},
			},
		},
	}).Run())

}
